import 'dart:async';
import 'package:ai_model/app/core/network/core/api_client.dart';
import 'package:ai_model/app/core/network/extensions/auth_api_extension.dart';
import 'package:ai_model/app/core/storage/pref_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../routes/app_pages.dart';

class LoginController extends GetxController {
  final phoneController = TextEditingController();
  final smsCodeController = TextEditingController();

  final RxBool isPhoneValid = false.obs;
  final RxBool isSmsCodeValid = false.obs;
  final RxBool isCountingDown = false.obs;
  final RxString tipStr = ''.obs;
  final RxInt countdown = 60.obs;
  final RxBool isAgreementChecked = false.obs;

  Timer? _timer;

  @override
  void onClose() {
    phoneController.dispose();
    smsCodeController.dispose();
    _timer?.cancel();
    super.onClose();
  }

  // Validate phone number format
  void validatePhone(String phone) {
    isPhoneValid.value =
        phone.trim().length == 11 && RegExp(r'^1[3-9]\d{9}$').hasMatch(phone);
  }

  // Validate SMS code
  void validateSmsCode(String code) {
    isSmsCodeValid.value =
        code.trim().length == 6 && RegExp(r'^\d{6}$').hasMatch(code);
  }

  // Toggle agreement checkbox
  void toggleAgreement() {
    isAgreementChecked.value = !isAgreementChecked.value;
  }

  // Send verification code to phone number
  Future<void> sendVerificationCode() async {
    if (!isPhoneValid.value) {
      Get.snackbar('提示', '请输入正确的手机号码');
      return;
    }

    try {
      // Show loading indicator
      Get.dialog(const Center(child: CircularProgressIndicator()),
          barrierDismissible: false);

      // 调用发送验证码接口
      final response =
          await ApiClient().sendLoginSMSCaptcha(phoneController.text);
      Get.back(); // Dismiss loading indicator

      if (response.isSuccess) {
        // Start countdown
        startCountdown();
        Get.snackbar('成功', '验证码已发送');
      } else {
        Get.snackbar('错误', response.message);
      }
    } catch (e) {
      Get.back(); // Dismiss loading indicator
      Get.snackbar('错误', '发送失败，请重试');
      print('Error sending verification code: $e');
    }
  }

  // Start countdown timer for SMS resend
  void startCountdown() {
    isCountingDown.value = true;
    countdown.value = 60;

    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        isCountingDown.value = false;
        _timer?.cancel();
      }
    });
  }

  // Login with phone and verification code
  Future<void> login() async {
    if (!isPhoneValid.value) {
      Get.snackbar('提示', '请输入正确的手机号码');
      return;
    }

    if (!isSmsCodeValid.value) {
      tipStr.value = '验证码输入错误';
      return;
    }

    if (!isAgreementChecked.value) {
      Get.snackbar('提示', '请先阅读并同意用户协议');
      return;
    }

    try {
      Get.dialog(const Center(child: CircularProgressIndicator()),
          barrierDismissible: false);

      // 调用登录接口
      final response = await ApiClient()
          .doLoginBySMSCaptcha(phoneController.text, smsCodeController.text);
      Get.back();

      if (response.isSuccess && response.data != null) {
        // 保存用户token到本地
        final userToken = response.data!.data?.token ?? '';
        await PrefUtils().setToken(userToken);
        await PrefUtils().setPhoneNumber(phoneController.text);

        Get.snackbar('成功', '登录成功');

        // 跳转到首页
        Get.offAllNamed(Routes.HOME);
      } else {
        tipStr.value = response.message;
        Get.snackbar('错误', response.message);
      }
    } catch (e) {
      Get.back();
      Get.snackbar('错误', '登录失败，请重试');
      print('Error during login: $e');
    }
  }

  // Navigate to register page
  void goToRegister() {
    Get.toNamed(Routes.REGISTER);
  }
}
